<?php
/**
 * 添加单条item
 * author: JiangJun
 * CreateTime:2021/7/25 22:11
 */


require '../vendor/autoload.php';

use Aws\DynamoDb\Exception\DynamoDbException;
use Aws\DynamoDb\Marshaler;

$sdk = new Aws\Sdk([
    'region'   => 'us-west-2',
    'version'  => 'latest'
]);

$dynamodb = $sdk->createDynamoDb();
$marshaler = new Marshaler();

$tableName = 'Movies';

$year = 2015;
$title = 'The Big New Movie';

//官方给的例子，传入的是Json字符串
$item = $marshaler->marshalJson('
    {
        "year": ' . $year . ',
        "title": "' . $title . '",
        "info": {
            "plot": "Nothing happens at all.",
            "rating": 0
        }
    }
');

//自己写的一个例子,传入的是数组,注意调用的方法和上面的不同
$jjItem=$marshaler->marshalItem([
    'year'=>2021,
    'title'=>'Jiang Jun',
    'info'=>[
        'plot'=>'ppp',
        'rating'=>5,
    ]
]);

$params = [
    'TableName' => 'Movies',
    'Item' => $jjItem,
    //加上这个条件后，如果key重复，就不会添加成功。不加这个条件的话，重复的key会导致更新
    //这里有点怪，括号里只能传一个参数，也就是 partion key。但其实会验证，partion key 和sort key，是否存在
    'ConditionExpression'=>'attribute_not_exists(#yr)',
    'ExpressionAttributeNames'=> [ '#yr' => 'year' ],//属性名
];


try {
    $result = $dynamodb->putItem($params);
    echo "Added item success" . PHP_EOL;

} catch (DynamoDbException $e) {
    echo "Unable to add item:\n";
    echo $e->getMessage() . "\n";
}
